import {
  VuexModule,
  Module,
  Action,
  Mutation,
  getModule
} from 'vuex-module-decorators'
import { loginAPI, getUserInfoAPI, getUserInfoByIdAPI } from '@/api/users'
import {
  getToken,
  setToken,
  removeToken,
  setTime,
  removeTime
} from '@/utils/cookies'
import { resetRouter } from '@/router'
// import { PermissionModule } from './permission'
// import { TagsViewModule } from './tags-view'
import store from '@/store'
// import { remove } from 'js-cookie'
// config.rawError = true

export interface IUserInfo {
  username: string
  staffPhoto: string
  company: string
  companyId: number
  // authCacheKey: null
  // mobile: string
  roles: any
  userId: string
}

export interface IUserState {
  token?: string
  userInfo: IUserInfo
}

@Module({ dynamic: true, store, name: 'user' })
class User extends VuexModule implements IUserState {
  /*
    ! state
  */
  token? = getToken() || undefined
  userInfo = {
    username: '',
    staffPhoto: '',
    companyId: 0,
    company: '',
    // authCacheKey null,
    // mobile: '',
    roles: {},
    userId: ''
  }

  /*
    ! getters
  */
  get username(): string {
    return this.userInfo.username
  }

  get avatar(): string {
    return this.userInfo.staffPhoto
  }

  get company(): string {
    return this.userInfo.company
  }

  get companyId(): number {
    return this.userInfo.companyId
  }

  get userId(): string {
    return this.userInfo.userId
  }

  get roles(): any {
    return this.userInfo.roles
  }

  get hrToken(): string | undefined {
    return this.token
  }

  /*
    ! mutations
  */
  //  存入 token
  @Mutation
  private SET_TOKEN(token: string) {
    this.token = token
    setToken(token)
    setTime()
  }

  // 删除 token
  @Mutation
  private DEL_TOKEN() {
    this.token = undefined
    removeToken()
    removeTime()
  }

  // 存入用户信息
  @Mutation
  private SET_USER_INFO(data: IUserInfo) {
    this.userInfo = data
  }

  // 清理用户信息
  @Mutation
  private DEL_USER_INFO() {
    this.userInfo = {
      username: '',
      staffPhoto: '',
      company: '',
      companyId: 0,
      // authCacheKey: null,
      // mobile: '',
      roles: {},
      userId: ''
    }
  }

  /*
    ! actions
  */
  // ? 登录
  @Action
  public async login(userInfo: { mobile: string, password: string }) {
    const res = await loginAPI({ ...userInfo })
    this.SET_TOKEN(<string>res)
  }

  // ? 获取用户信息
  @Action
  public async getUserInfo() {
    try {
      const res = await getUserInfoAPI()
      res.staffPhoto = (await getUserInfoByIdAPI(<string>res.userId)).staffPhoto
      this.SET_USER_INFO(res)
    } catch (error) {
      console.log(error)
    }
  }

  // ? 退出登录
  @Action
  public async logout() {
    resetRouter()
    // ;(this as any).store.commit('DEL_TOKEN')
    // ;(this as any).store.commit('DEL_USER_INFO')
    this.DEL_TOKEN()
    this.DEL_USER_INFO()
  }
}

export const UserModule = getModule(User)
